package com.kingtone.rongji.ui;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.kingtone.rongji.MainActivity;
import com.kingtone.rongji.OrderDetailActivity;
import com.kingtone.rongji.OrderListActivity;
import com.kingtone.rongji.R;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;


public class CancelOrderDialog {
	/**
	 * 为了确保整个应用同时只会弹出一个弹框，此处使用单例对象，每次显示下一个ALert之前调用dismiss关掉上一个弹框。
	 */
	private static Dialog mDialog;
	private static int reasonType = 0;
	private CancelOrderDialog() {
	}
	
	/**
	 * 关闭自定义弹框
	 */
	public static void dismiss() {
		if(null != mDialog && mDialog.isShowing()) {
			mDialog.dismiss();
		}
	}

	
	public static Dialog show(final Activity activity,final String orderNum, OnClickListener dismissAction) {
		// 逻辑异常的时候，可能在自定义Alert显示的情况下又去调用show方法，这里日志进行记录
		if(null != mDialog && mDialog.isShowing()) {
			Log.e("CustomDialog", "Auto close alert for show next alert.The pre alert:" + mDialog);
		}
		
		// 隐藏可能存在的上一个Alert
		dismiss();
		
		if (null == activity) {
			return null;
		}

		Dialog dlg = new Dialog(activity,R.style.CustomDialogStyle);
		dlg.show();
		
		Window window = dlg.getWindow();
		window.setBackgroundDrawable(new ColorDrawable(0));
		window.setContentView(R.layout.cancel_order_dialog);

		TextView orderNo = (TextView)window.findViewById(R.id.cancel_order_id);
		orderNo.setText(activity.getString(R.string.order_text) + orderNum);
		final Spinner spinner = (Spinner)window.findViewById(R.id.spinner_cancel_reasons);
		spinner.setPrompt("请选择原因");
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity, R.array.cancel_reason_item, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
    	{	
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) 
			{					
						/*0 = 现在不想购买
						1 = 支付不成功
						2 = 商品价格较贵
						3 = 等待时间过长
						4 = 有商品缺货
						5 = 更换或添加新商品
						6 = 错误或重复下单
						7= 其它原因（需要填写备注）*/

				//String reason = spinner.getSelectedItem().toString();
				reasonType = arg2 -1;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
    	});
		final EditText cancelEditText = (EditText)window.findViewById(R.id.cancel_reasons);
		
		cancelEditText.setFocusable(true);   
		cancelEditText.setFocusableInTouchMode(true);   
		cancelEditText.requestFocus();  
		Button btnConfirm= (Button)window.findViewById(R.id.cancel_comment_summit);
		btnConfirm.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				String reason = cancelEditText.getText().toString();
				cancelOrder(activity, orderNum, reason,reasonType);
			}
		});
		
		Button btnClose = (Button)window.findViewById(R.id.cancel_close_dialog);
		btnClose.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				dismiss();
			}
		});
		mDialog = dlg;
		return dlg;
	}
	
	/**
	 * 
	 * @param context
	 * @param orderNum
	 * @param reason
	 * @param resonType
	 */
	private static void cancelOrder(final Context context,final String orderNum, String reason, int resonType)
	{
		String userId = SharedPreferencesUtil.getInstance(context).getString(AppContasts.USERID_KEY);
		
		RongJiRestClient.cancelOrder(userId, orderNum, reason, resonType, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(context);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				String result = new String(arg2);
				Log.d("cancelOrder failure ", result);
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					JSONTokener jsonParser = new JSONTokener(result);  
				    try {
						JSONObject address = (JSONObject) jsonParser.nextValue();
						boolean errorCode = address.optBoolean("Status");
						if(errorCode)
						{
							dismiss();
							Toast.makeText(context, context.getString(R.string.cancel_order_success), Toast.LENGTH_SHORT).show();
							Intent intent = new Intent(context, OrderListActivity.class);
							intent.putExtra("flag", AppContasts.ORDER_TYPE_CANCELED);
							context.startActivity(intent);
							 
						}else
						{
							String errorMsg = address.optString("ErrorMessage");
							if(!TextUtils.isEmpty(errorMsg))
							{
								Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
							}
						}
						
				    } catch (JSONException e) {
						e.printStackTrace();
					} 
                    
				}
			}	
		});
	}

}
